package com.aiyige.page.my.view;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.model.moment.entity.ViewRecord;
import com.aiyige.model.request.MyViewRequest;
import com.aiyige.model.response.MyViewListResponse;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.HighLightWordUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.CommonDataView;
import com.aiyige.utils.widget.MyEditText;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.vondear.rxtools.RxKeyboardTool;

import net.cachapa.expandablelayout.ExpandableLayout;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import timber.log.Timber;

/**
 * Created by xiachao on 2017/11/29.
 */
@Track("浏览记录")
@Route(path = ARouterConfig.MyViewPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class MyViewsPage extends BaseActivity implements CommonDataView.RetrofitStub, MyViewAdapter.DeleteCallback {

    private static final String TAG = "MyViewPage";

    @BindView(R.id.cdv)
    CommonDataView cdv;

    MyViewAdapter adapter;

    @BindView(R.id.et_search)
    MyEditText inputEt;

    @BindView(R.id.cancelLayout)
    ExpandableLayout cancelLayout;

    @BindView(R.id.tv_edit)
    TextView tvEdit;

//    TextWatcher searchTextWatcher;

    boolean selectAll = false;

    private boolean isEdit = false;

    @BindView(R.id.rl_bottom)
    RelativeLayout llBottom;

    @BindView(R.id.iv_item_selection)
    ImageView tvSelection;


    public static void start() {
        ARouter.getInstance().build(ARouterConfig.MyViewPage).navigation();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_my_views);
        ButterKnife.bind(this);
        initViews();
    }

    private void initViews() {
        adapter = new MyViewAdapter();
        cdv.config(adapter, this);
        cdv.setRecyclerViewBgColor(ContextCompat.getColor(this, R.color.zwcolor_gray_f4f8f9));
        cdv.addItemDecoration(1, R.color.zwcolor_gray_f4f8f9);
        inputEt.setEditTextHint(getString(R.string.search));
        inputEt.getEditText().setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showSearchResultPanel();
                }
            }
        });
        inputEt.setActionSearch(new MyEditText.ActionCallback() {
            @Override
            public void actionSearch(String value) {
                doSearch();
            }
        });
        inputEt.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s != null) {//此逻辑是用于修复： 编辑状态，用户输入了没有内容的搜索结果，当用户删除关键字后，还原到原来的内容
                    String value = s.toString();
                    if (isEmpty(value)) {
                        doSearch();
                    }
                }
            }
        });
        adapter.setCallback(this);
        cdv.doRefreshRequest();
    }


    @Override
    public Call<ResponseBody> call(long currentPage) {
        return MyViewRequest.newBuilder()
                .pageNum((int) currentPage)
                .keyWord(getSearchValue())
                .build();
    }

    private String getSearchValue() {
        return isEmpty(inputEt.getEditText().getText().toString().trim()) ? "" : inputEt.getEditText().getText().toString().trim();
    }


    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            MyViewListResponse homeResponse = JsonUtil.toObject(respJson, MyViewListResponse.class);
            if (ListUtil.isEmpty(homeResponse.getContent())) {
                resultList.addAll(new LinkedList());
                return new CommonDataView.HandleResult(homeResponse.isLast());
            } else {
                if (!ListUtil.isEmpty(homeResponse.getContent())) {
                    for (ViewRecord viewRecord : homeResponse.getContent()) {
                        try {
                            viewRecord.setSeach(!TextUtils.isEmpty(getSearchValue()));
                            viewRecord.setMomentTitle(HighLightWordUtil.highLight(viewRecord.getMomentTitle(), getSearchValue()));
                        } catch (Exception e) {
                            Timber.e("handleResponse:" + Log.getStackTraceString(e));
                        }
                    }
                }
                resultList.addAll(homeResponse.getContent());
                editEnabled(!resultList.isEmpty());
                return new CommonDataView.HandleResult(homeResponse.isLast());
            }
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }

    }


    public void showSearchResultPanel() {
        cdv.setVisibility(View.VISIBLE);
    }


    private void doSearch() {
        if (isEdit) {
            setEdit(!isEdit);
        }
        cdv.refresh();
        RxKeyboardTool.hideSoftInput(this);
    }

    private void setSelectAll() {
        if (adapter == null) {
            return;
        }
        adapter.selectAll();
    }

    private void setUnSelectAll() {
        if (adapter == null) {
            return;
        }
        adapter.unSelectAll();
    }

    private void deleteSelected() {
        if (adapter == null) {
            return;
        }
        if (adapter.getSelectedList() == null || adapter.getSelectedList().isEmpty()) {
            ToastX.show(MyApp.getAppContext().getString(R.string.please_select_views_data));
            return;
        }
        new AlertDialog.Builder(this).setTitle(getString(R.string.alert_delete))
                .setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        adapter.deleteSelected();
                        if (ListUtil.isEmpty(adapter.getData())) {
                            setEdit(false);
                        }
                        dialog.dismiss();
                    }
                }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();

    }

    public void setEdit(boolean edit) {
        if (adapter.getData() == null
                || adapter.getData().isEmpty()) {
            deleteCallback();
            return;
        }
        isEdit = edit;
        adapter.setEdit(isEdit);
        tvEdit.setText(getString(isEdit ? R.string.cancel_edit : R.string.edit));
        llBottom.setVisibility(isEdit ? View.VISIBLE : View.GONE);

    }

    @OnClick({R.id.rl_title_layout, R.id.titleBackBtn, R.id.tv_edit, R.id.ll_select_all, R.id.tv_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_title_layout:
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.tv_edit:
                setEdit(!isEdit);
                break;
            case R.id.ll_select_all:
                selectAll = !selectAll;
                tvSelection.setSelected(selectAll);
                if (selectAll) {
                    setSelectAll();
                } else {
                    setUnSelectAll();
                }
                break;
            case R.id.tv_delete:
                deleteSelected();
                break;
        }
    }

    public void editEnabled(boolean enabled) {
        tvEdit.setTextColor(ContextCompat.getColor(this, enabled ? R.color.zwcolor_black_111111 : R.color.zwcolor_gray_b1b5c1));
        tvEdit.setEnabled(enabled);
        if (isEdit) {
            tvEdit.setText(getString(!enabled ? R.string.edit : R.string.cancel_edit));
            llBottom.setVisibility(enabled ? View.VISIBLE : View.GONE);
            if (!enabled) {
                selectAll = false;
                tvSelection.setSelected(selectAll);
            }
        }
    }

    @Override
    public void deleteCallback() {
        boolean isEmpty = adapter.getData() == null
                || adapter.getData().isEmpty();
        editEnabled(!isEmpty);
    }

    @Override
    public void unSelectCallback() {
        if (selectAll) {
            selectAll = !selectAll;
            tvSelection.setSelected(selectAll);
        }
    }
}
